package biz.datalk.industrialland.common.component.filter;

import biz.datalk.commons.utils.IdProvider;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author tarofang@163.com
 * @date 2021-10-28
 */
public class MDCFilter implements Filter {

    public static final String TRACE_ID_HEADER = "x-trace-id";
    public static final String TRACE_ID = "traceId";
    public static final String DEFAULT_TRACE_ID = "0";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        initTraceId((HttpServletRequest) request);
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        MDC.clear();
    }

    private void initTraceId(HttpServletRequest request) {
        String traceId = request.getHeader(TRACE_ID_HEADER);
        if (StringUtils.isBlank(traceId) || StringUtils.equals(DEFAULT_TRACE_ID, traceId)) {
            traceId = IdProvider.createUUIDId();
        }

        MDC.put(TRACE_ID, traceId);
    }
}
